package com.ruge.tool.excelTool;

import com.alibaba.excel.EasyExcel;
import com.ruge.tool.json.JsonTool;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * description excel工具类
 * create Time at 2022/6/21 15:36
 *
 * @author alice.ruge
 * @since 0.0.7
 */
public class ExcelTool {

    public static <T> void download(HttpServletResponse response, Class<T> clazz, String sheetName, Collection<?> data, String fileName) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }

    /**
     * 不创建对象的导出
     *
     * @param data     {@link MapWriteData}
     * @param response {@link HttpServletResponse}
     * @throws IOException 异常信息
     */
    public static void mapDownload(MapWriteData data, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(data.getFileName(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream()).head(head(data.getHeadMap())).sheet(data.getFileName()).doWrite(dataList(data.getDataList(), data.getDataStrMap()));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(16);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JsonTool.getObjToJson(map));
        }
    }

    /**
     * 设置表头
     *
     * @param headMap 表头
     * @return 设置后的表头
     */
    private static List<List<String>> head(String[] headMap) {
        List<List<String>> list = new ArrayList<>();
        for (String head : headMap) {
            List<String> headList = new ArrayList<>();
            headList.add(head);
            list.add(headList);
        }
        return list;
    }

    /**
     * 设置导出的数据内容
     *
     * @param dataList   data
     * @param dataStrMap key
     * @return 导出的数据
     */
    private static List<List<Object>> dataList(List<Map<String, Object>> dataList, String[] dataStrMap) {
        List<List<Object>> list = new ArrayList<>();
        for (Map<String, Object> map : dataList) {
            List<Object> data = new ArrayList<>();
            for (int i = 0; i < dataStrMap.length; i++) {
                data.add(map.get(dataStrMap[i]));
            }
            list.add(data);
        }
        return list;
    }
}
